package org.porridge.prdblog.article.business;

import java.util.Date;
import java.util.List;

import org.db.createsql.AbstrDao;
import org.porridge.module.fun.po.Fun;
import org.porridge.module.main.po.User;
import org.porridge.prdblog.article.dao.ArticleDao;
import org.porridge.prdblog.article.po.Accessory;
import org.porridge.prdblog.article.po.Article;
import org.porridge.prdblog.label.po.Label;
import org.porridge.prdblog.label.po.LabelArt;
import org.porridge.util.BaseUtil;
import org.porridge.util.Constant;
import org.porridge.util.jqgrid.GridPO;

/**
 * 文章添加逻辑层
* @Title: ArticleBusiness.java 
* @Package org.porridge.prdblog.article.business 
* @Description: TODO 
* @author porridge
* @url  http://www.prdblog.com/
* @email  mfkwfc@gmail.com   
* @date 2014年4月21日 下午10:43:55 
* @version V1.0
 */
public class ArticleBusiness extends AbstrDao<ArticleDao>{
	
	/**
	 * 查询表格数据
	 * @param grph
	 * @return
	 * @throws Exception
	 */
	public String jqgrid(GridPO grph) throws Exception{
		String ret="";
		if(grph!=null){
			ret=this.absDao.getListJqgrid(Article.class,grph.getFilename(),grph.getWhere(),grph.getSidx(),grph.getSord(),grph.getPage(),grph.getRows());
		}
		return ret;
	}
	/**
	 * 修改单条文章数据
	 * @param art
	 * @return
	 * @throws Exception
	 */
	public boolean updateArticle(Article art) throws Exception{
		boolean bl=false;
		Fun fun=findFuncls(art.getCls());
		if(fun!=null && "3".equals(fun.getType()) && ("1".equals(fun.getFtltype()) || "2".equals(fun.getFtltype()))){
			if(this.absDao.getCount(Article.class,"id='"+art.getId()+"'")!=0){
				setBreviary(art);
				if(this.absDao.update(art)>0){
					saveAffix(art,art.getId());
					bl=true;
				}
			}
		}
		return bl;
	}
	/**
	 * 保存文章
	 * 保存成功后需要处理
	 * 1  保存标签
	 * 2 保存图片
	 * @param art
	 * @return
	 * @throws Exception 
	 */
	public String saveArticle(Article art,User user) throws Exception{
		String ret="{\"result\":false,\"name\":null,\"text\":\"类型数据读取失败,请刷新重试\"}";
		Fun fun=findFuncls(art.getCls());
		if(fun!=null && "3".equals(fun.getType()) && ("1".equals(fun.getFtltype()) || "2".equals(fun.getFtltype()))){
			if("1".equals(fun.getFtltype())){//单页只允许存在一条数据,先删除他存在的数据.再添加
				delOneCls(fun.getCls());
				art.setLabletype("0");
			}else
				art.setLabletype("1");
			art.setTop("");
			art.setAdduserid(user.getId());
			art.setAddusername(user.getRealname());
			setBreviary(art);
			if(art.getTid()!=null && art.getTid().trim().length()>0){
				if(this.absDao.getCount(Article.class,"id='"+art.getTid()+"'")==0){
					art.setId(art.getTid());
				}
			}
			String uid=this.absDao.save(art);
			if(uid!=null){
				ret="{\"result\":true}";
				saveAffix(art,uid);
			}
		}
		return ret;
	}
	/**
	 * 生成文章缩略显示以及目录结构
	 * 主要是靠判断</p> 来实现效果.靠这个做为段落标识
	 */
	private void setBreviary(Article art){
		int maxlen=Integer.valueOf(Constant.SETTING.getPage_breviary());
		if(art.getAtr_content().length()>maxlen){
			String temp=art.getAtr_content().substring(maxlen,art.getAtr_content().length());
			maxlen+=temp.indexOf("</p>")+4;
			art.setBreviary(art.getAtr_content().substring(0,maxlen)+"...");
		}else
			art.setBreviary(art.getAtr_content());
		
		if(art.getAtr_content().indexOf("<h1>")!=-1){
			String cnt=art.getAtr_content();
			String catalog="";
			int len=0;
			
			int h1=1;
			int h2=1;
			int maxh2=0;
			while(true){
				//取第二层目录
				if(cnt.indexOf("<h2>")!=-1 && catalog.length()>0){
					h2=1;
					while(true){
						if(cnt.indexOf("<h2>")!=-1 && (cnt.indexOf("<h1>")==-1 || cnt.indexOf("<h1>")>cnt.indexOf("<h2>"))){
							len=cnt.indexOf("<h2>")+4;
							cnt=cnt.substring(len,cnt.length());
							catalog+="<dd eq=\""+maxh2+"\"><span>"+(h1-1)+"."+h2+"</span>"+cnt.substring(0,cnt.indexOf("</h2>")).trim()+"</dd>";
							cnt=cnt.substring(cnt.indexOf("</h2>")+5,cnt.length());
							++h2;
							++maxh2;
						}else
							break;
					}
				}
				if(cnt.indexOf("<h1>")!=-1){
					//取第一层目录
					len=cnt.indexOf("<h1>")+4;
					cnt=cnt.substring(len,cnt.length());
					catalog+="<dt eq=\""+(h1-1)+"\"><span>"+h1+"</span>"+cnt.substring(0,cnt.indexOf("</h1>")).trim()+"</dt>";
					cnt=cnt.substring(cnt.indexOf("</h1>")+5,cnt.length());
					++h1;
				}else
					break;
			}
			art.setCatalog(catalog);
		}
	}
	/**
	 * 通过code查询其是否是单条文章数据.如果是则返回
	 * @param code
	 * @return
	 * @throws Exception 
	 */
	public Article findArticleCode(String code) throws Exception{
		Fun fun=findFuncls(code);
		Article art=null;
		if(fun!=null &&  "3".equals(fun.getType()) && "1".equals(fun.getFtltype())){
			List<Article> arts=this.absDao.getList(Article.class,"*","cls='"+code+"'");
			if(arts.size()>0)
				art=arts.get(0);
		}
		return art;
	}
	/**
	 * 根据类型查询单条功能表数据
	 * @param cls
	 * @return
	 * @throws Exception 
	 */
	private Fun findFuncls(String cls) throws Exception{
		Fun fun=null;
		List<Fun> funs=this.absDao.getList(Fun.class,"*","funcode='"+cls+"'");
		if(funs.size()>0)
			fun=funs.get(0);
		return fun;
	}
	/**
	 * 根据类型删除他当前的数据
	 * @param cls
	 * @throws Exception 
	 */
	private void delOneCls(String cls) throws Exception{
		List<Article> arts=this.absDao.getList(Article.class,"*","cls='"+cls+"'");
		for(Article a:arts)
			delArticle(a.getId());
	}
	/**
	 * 删除文章
	 * @param id
	 * @throws Exception
	 */
	public boolean delArticle(String id) throws Exception{
		boolean bl=false;
		if(this.absDao.dele(Article.class,"id='"+id+"'")>0){
			this.absDao.dele(LabelArt.class,"aid='"+id+"'");
			this.absDao.dele(Accessory.class,"aid='"+id+"'");
			bl=true;
		}
		return bl;
	}
	/**
	 * 负责处理图片附件以及标签
	 * @param art
	 * @param uid
	 * @throws Exception 
	 */
	private void saveAffix(Article art,String uid) throws Exception{
		this.absDao.dele(LabelArt.class,"aid='"+uid+"'");
		this.absDao.dele(Accessory.class,"aid='"+uid+"'");
		//处理标签
		if(art.getLablename()!=null && art.getLablename().trim().length()>0){
			String[] lbs=art.getLablename().split(",");
			for(String l:lbs){
				if(l.trim().length()>0){
					LabelArt lat=new LabelArt();
					lat.setAid(uid);
					lat.setLid(findLable(l.trim()));
					lat.setAddtime(BaseUtil.convertDate(new Date(),"yyyy-MM-dd"));
					this.absDao.save(lat);
				}
			}
		}
		if(art.getAccid()!=null && art.getAccid().trim().length()>0){
			String[] acs=art.getAccid().split(",");
			for(String ac:acs){
				if(ac!="" && ac.indexOf("####")!=-1){
					String[] as=ac.split("####");
					if(as.length==2){
						Accessory aces=new Accessory();
						aces.setAid(uid);
						aces.setHash(as[0].trim());;
						aces.setAddress(as[1].trim());
						this.absDao.save(aces);
					}
				}
			}
		}
	}
	/**
	 * 根据名称查询出标签id
	 * 如果不存在则添加该标签
	 * @param text
	 * @return
	 * @throws Exception 
	 */
	public String findLable(String text) throws Exception{
		List<Label> lbs=this.absDao.getList(Label.class,"*","name='"+text+"'");
		if(lbs.size()>0)
			return lbs.get(0).getId();
		else{
			Label label=new Label();
			label.setName(text);
			label.setAddtime(BaseUtil.convertDate(new Date(),"yyyy-MM-dd"));
			return this.absDao.save(label);
		}
	}
}
